package com.ftg.midamall.comm.tool;

import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * 通用令牌处理类
 * @author qjw
 * @version 1.0
 * @date 2023/10/20 14:40
 */

public class TokenUtil {
    public static final String SECRET = "WY!@#F^%A";

    /**
     * 根据传递给我的userinfo生成用户令牌
     * @param userinfo  用户信息
     * @return  String 令牌
     */
    public static String createToken(JSONObject userinfo){
        // 过期时间，60s
        Calendar expires = Calendar.getInstance();
        expires.add(Calendar.SECOND, 600000000);

        Map<String,Object> headers = new HashMap<>(2);
        headers.put("alg","HS256");
        headers.put("typ","JWT");
// 取出用户信息部分
        JSONObject data = JSONObject.from(userinfo.get("data"));

        String jwtToken = JWT.create()
                // 第一部分Header
                .withHeader(headers)
                // 第二部分Payload
                .withClaim("id", data.getLong("id"))
                .withClaim("username", data.getString("username"))
                .withClaim("icon", data.getString("icon"))
                .withClaim("email", data.getString("email"))
                .withClaim("nickName", data.getString("nickName"))
                .withClaim("note", data.getString("note"))
                .withClaim("createTime", data.getString("createTime"))
                .withExpiresAt(expires.getTime())
                // 第三部分Signature
                .sign(Algorithm.HMAC256(SECRET));
        return jwtToken;
    }

    /**
     * 解析token
     *
     * @param token  令牌
     * @return 对象
     */

    public static JSONObject parseTokenWithObject(String token) {
        JWTVerifier jwtVerifier =JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT decodedJWT  = jwtVerifier.verify(token);

        Claim id =decodedJWT.getClaim("id");
        Claim userName = decodedJWT.getClaim("username");
        Claim icon = decodedJWT.getClaim("icon");
        Claim email = decodedJWT.getClaim("email");
        Claim nickName = decodedJWT.getClaim("nickName");
        Claim note = decodedJWT.getClaim("note");
        Claim createTime = decodedJWT.getClaim("createTime");

        JSONObject json =new JSONObject();
        json.put("id",id.asLong());
        json.put("userName", userName.asString());
        json.put("icon", icon.asString());
        json.put("email", email.asString());
        json.put("nickName", nickName.asString());
        json.put("note", note.asString());
        json.put("createTime", createTime.asString());

        return json;

    }
}
